/**
 * 
 */
package vn.edu.fpt.xml.hrm.controller.auth;

import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.XMLStreamException;

import vn.edu.fpt.xml.hrm.controller.AbstractController;
import vn.edu.fpt.xml.hrm.pojo.Projectlist;

/**
 * Run when user click login button
 * @author Yoshimi
 *
 */
public class LoginController extends AbstractController {

    private boolean found;
    private String DisplayName;
    private final String invalidPage = "index.jsp";
    private final String homePage = "welcome.jsp";
    private String username;
    private String password;

    /* (non-Javadoc)
     * @see vn.edu.fpt.xml.hrm.controller.AbstractController#execute()
     */
    @Override
    protected String execute() {
        // TODO Auto-generated method stub
        HttpServletRequest request = this.getRequest();
        HttpServletResponse response = this.getResponse();
        String button = request.getParameter("btnAction");

        found = false;
        DisplayName = "";
        String url = invalidPage;
        if (button.equals("Login")) {
            String username = request.getParameter("txtUsername");
            String password = request.getParameter("txtPassword");
            LoginObjJDBC login = new LoginObjJDBC(username, password);
            boolean result = login.checkLogin();

            if (result == true) {
                try {
                    boolean admin = login.isAdmin();
                    //String status = login.checkStatus();
                    Projectlist.importXML(getServletContext().getRealPath("/") + "WEB-INF/project.xml");
                    String role;
                    if (admin == true) {
                        role = "admin";
                    } else {
                        role = "employee";
                    }
                    HttpSession session = request.getSession(true);
                    session.setAttribute("USER", login.getDisplayname());
                    session.setAttribute("EMPLOYEEID", login.getEmployeeid());
                    session.setAttribute("ROLE", role);
                    url = homePage;
                    //                    if(admin){
                    //                        response.sendRedirect(adminPage);
                    //                    }else if(!active){
                    //                        response.sendRedirect(suspendPage);
                    //                    }else{
                    //                    response.sendRedirect(searchPage);
                    //                    }
                } catch (NamingException ex) {
                    Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (XMLStreamException ex) {
                    Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //request.setAttribute("FAILED", login.getFailed());
            return url;
        }
        return null;
    }
    /*protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try{
    String button = request.getParameter("btnAction");
    String username = request.getParameter("txtUsername");
    String password = request.getParameter("txtPassword");
    if (button.equals("Login")) {
    String webPath = getServletContext().getRealPath("/");
    String filePath = webPath + "WEB-INF/user.xml";
    Document doc = XMLUtil.createDOMTree(filePath);
    found = false;
    DisplayName = "";
    checkLogin(username, password, doc);
    String url = invalidPage;
    if (found) {
    HttpSession session = request.getSession();
    session.setAttribute("DISPLAYNAME", DisplayName);
    url = homePage;
    }
    RequestDispatcher rd = request.getRequestDispatcher(url);
    rd.forward(request, response);
    }
    } catch (Exception e){
    e.printStackTrace();
    } finally {
    out.close();
    }
    }*/
    /*private void checkLogin(String username, String password, Node node){
    if (node == null) {
    return;
    }
    if (node.getNodeName().equals("User")){
    String id = node.getAttributes().getNamedItem("UserName").getNodeValue();
    if (id.equals(username)) {
    NodeList timesheetChildren = node.getChildNodes();
    for (int i= 0; i < timesheetChildren.getLength(); i++) {
    Node tmp = timesheetChildren.item(i);
    if (tmp.getNodeName().equals("DisplayName")) {
    this.DisplayName= tmp.getTextContent().trim();
    continue;
    }
    if (tmp.getNodeName().equals("Password")) {
    String pass = tmp.getTextContent().trim();
    if (pass.equals(password)) {
    Node sibling = tmp.getNextSibling();
    while (!sibling.getNodeName().equals("Status")){
    sibling = sibling.getNextSibling();
    }
    String status = sibling.getTextContent().trim();
    if (!status.equals("dropout")) {
    found = true;
    return;
    }
    }
    }
    }
    }
    }
    NodeList children = node.getChildNodes();
    int i =0;
    while (i<children.getLength()){
    checkLogin(username, password, children.item(i++));
    }
    }
     */
}
